#!/usr/bin/env bash

#get this script real directory
SOURCE="$0"
while [ -h "$SOURCE"  ]; do # resolve $SOURCE until the file is no longer a symlink
    this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"
    SOURCE="$(readlink "$SOURCE")"
    # if $SOURCE was a relative symlink, 
    #we need to resolve it relative to the path 
    #where the symlink file was located
    [[ $SOURCE != /*  ]] && SOURCE="$this_script_dir/$SOURCE"
done
this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"

##config file path and file content:
#~/git/cfg/remote_host.cfg
#user!-!ip!-!passwd!-!id!-!ssh_port!-!description

config_file_name="$(cd $this_script_dir/../cfg && pwd)/remote_host.cfg"
echo "cfg file is:$config_file_name"
expect_ssh_path="$this_script_dir/vlogin.sh"
show_fmt="%24s%14s%8s %s\n";

#param:
#   1,username 2,ip 3,passwd 4,id 5,description
print_one_host_info()
{
    pass=$3;
    if [ 16 -lt ${#pass} ];then
        show_passwd="???";
        show_description="???"
    else
        show_passwd=$3;
        show_description=$5;
    fi
    uip=$1"@"$2;

    printf "$show_fmt" \
        "$uip" \
        "$show_passwd"  \
        "$4" \
        "[$show_description]"; 
    }

print_line()
{
    for((print_line_i=0;print_line_i<${1:-80};++print_line_i))
        {
            printf "-";
        }
    printf "\n";
}


###############################script entry##################

if [ ! -f "$config_file_name" ];then
    echo "file [$config_file_name],dose not exist!"
    exit
fi

if [ ! -f "$expect_ssh_path" ];then
    echo "file [$expect_ssh_path],dose not exist!"
    exit
fi

#temp_cfg=`mktemp`
#set variable in this shell
#read my private machine information
config_file_name_private="$HOME/Documents/private/remote_host_private.cfg"

if [  -f "$config_file_name_private" ];then
    eval `sed '/^[ ]*#/d' "$config_file_name_private" | \
        awk 'BEGIN{ FS="!-!" ; i=0 }
            {
                printf("user_name[%d]=\"%s\"\n\
                    host_ip[%d]=\"%s\"\n\
                    user_passwd[%d]='\''%s'\''\n\
                    id_of_ip[%d]=\"%s\"\n\
                    ssh_port[%d]=\"%s\"\n\
                    description[%d]='\''%s'\''\n",
                                    i,$1,
                                    i,$2,
                                    i,$3,
                                    i,$4,
                                    i,$5,
                                    i,$6);

                                    ++i;
                                }  
                            END{printf("index_of_item=%d",i)}'` 
                        else
                            index_of_item=0;
fi

eval `sed -e '/^[ ]*#/d' -e '/^[[:space:]]*$/d' "$config_file_name" | \
    awk 'BEGIN{ FS="!-!" ; i='$index_of_item'}
    {
        printf("user_name[%d]=\"%s\"\n\
            host_ip[%d]=\"%s\"\n\
            user_passwd[%d]='\''%s'\''\n\
            id_of_ip[%d]=\"%s\"\n\
            ssh_port[%d]=\"%s\"\n\
            description[%d]='\''%s'\''\n",
                    i,$1,
                    i,$2,
                    i,$3,
                    i,$4,
                    i,$5,
                    i,$6);

                    ++i;
                }  
            END{ }'` 

#trim space
for (( i=0; i < ${#user_name[*]}; ++i )); do
    user_name[i]=${user_name[i]% }
    host_ip[i]=${host_ip[i]% }
    user_passwd[i]=${user_passwd[i]% }
    id_of_ip[i]=${id_of_ip[i]% }
    ssh_port[i]=${ssh_port[i]% }
    description[i]=${description[i]% }
done

if [ "should_pwd" == "$1" ] && [ $# -ge 2 ] ;then #used for sl, which call s like: s should_pwd "echo info"
    should_show_pwd=true
    shift
elif [ "help" == "$1" ]||[ "pwd" == "$1" ]||[ "h" == "$1" ]||[ ! -n "$1" ];then
    num_of_host=${#user_name[*]}

    printf "$show_fmt" "user@ip" "passwd" "id" "description" ;
    print_line
    for((i=0;i<num_of_host;++i));do
        if [ ${#user_passwd[i]} -ge 12 ] ; then 
            user_passwd_show=${user_passwd[i]:0:8}***
        else
            user_passwd_show=${user_passwd[i]}
        fi

    #   1,username 2,ip 3,passwd 4,id 5,description
    [ "$1"x == "pwd"x ] && show_pwd=$user_passwd_show || show_pwd=***
    print_one_host_info "${user_name[i]}" \
        "${host_ip[i]}" \
        "$show_pwd" \
        "${id_of_ip[i]}" \
        "${description[i]}";
    done
    exit 0;
fi

#try to login the remote computer by ssh
for (( i=0; i<${#id_of_ip[*]}; ++i )); do
    if [ "${id_of_ip[i]}" = "$1" ]  ; then
        this_mac_ip=`/sbin/ifconfig -a`
        if [ "`whoami`" != "${user_name[i]}" ] || [ "127.0.0.1"x = "${host_ip[i]}"x ] \
            || ! echo "$this_mac_ip" | grep -i -E "${host_ip[i]}" \
            > /dev/null ; then
                    printf "$show_fmt" "user@ip" "passwd" "id" "description" ;
                    print_line #this function take variable namespace populate
                    #   1,username 2,ip 3,passwd 4,id 5,description
                        #"${user_passwd[i]}" \

                        if [ "$2"x == "pwd"x ] || [ "$should_show_pwd"x == "true"x ] ; then
                            show_pwd=${user_passwd[i]} 
                        else
                            show_pwd=***
                        fi

                        print_one_host_info "${user_name[i]}" \
                            "${host_ip[i]}" \
                        "$show_pwd" \
                        "${id_of_ip[i]}" \
                        "${description[i]}";

                    if [ -n "$2" ] ;then
                        echo "-- param4 is:$4"
                        eval "$expect_ssh_path ${user_name[i]} ${host_ip[i]} \
                            ${user_passwd[i]//$/\\$} \
                            ${ssh_port[i]} \
                            \"$2\" \
                            \"$3\"" 
                    else
                        eval "$expect_ssh_path ${user_name[i]} ${host_ip[i]} \
                            ${user_passwd[i]//$/\\$} \
                            ${ssh_port[i]}" 
                    fi

                    exit 0;

                else
                    printf "%s current machine's ip is already [ %s ],\
                        which you want to login.\n" "--" "${host_ip[i]}"
                                            exit 0;
        fi
    fi
done

#if do not find id in configure file
printf "id [%s] donot found in configure file,please check!\n" "$1"


exit 0;
